package org.example.yunshu.demos.websocket;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.yunshu.demos.constant.Constants;
import org.example.yunshu.demos.constant.WebSocketTypeEnum;
import org.example.yunshu.demos.mapper.*;
import org.example.yunshu.demos.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class MessageWebSocket extends TextWebSocketHandler {

    @Autowired
    private OnlineManager onlineManager ;

    @Autowired
    private FriendMapper friendMapper ;

    @Autowired
    private MessageMapper messageMapper ;

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private AddFriendMapper addFriendMapper ;

    @Autowired
    private SessionMapper sessionMapper ;

    private ObjectMapper objectMapper =  new ObjectMapper() ;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        UserInfo userInfo = (UserInfo) session.getAttributes().get(Constants.USERINFO_KEY);
        if(userInfo == null || userInfo.getUserId()<1){
            log.error("无法获取userInfo属性");
            return;
        }
        onlineManager.online(userInfo.getUserId(),session);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
         //处理message
        UserInfo userInfo = (UserInfo) session.getAttributes().get(Constants.USERINFO_KEY);
        if(userInfo == null || userInfo.getUserId()<1){
            log.error("无法获取userInfo属性");
            return;
        }
        ResponseMessage request = objectMapper.readValue(message.getPayload() , ResponseMessage.class);
         handleMessage(userInfo.getUserId(), request);
    }
//    处理消息
    private void handleMessage(Integer userId , ResponseMessage request) throws IOException {
           Integer type = request.getType() ;
           Integer sessionId = request.getSessionId();
           Integer fromId = request.getFromId();
           String fromName = request.getFromName();
           String content = request.getContent() ;
           Integer target = request.getTarget();
           String headImage = request.getHeadImage();
           switch (type){
               case 1:  {
                   // 先查会话是否还存在
                   ResponseMessage responseMessage = new ResponseMessage() ;
                    sessionId = sessionMapper.selectSessionId(sessionId);

                  if(sessionId == null || sessionId.equals(0)){

                      responseMessage.setType(WebSocketTypeEnum.ERROR.val);
                      responseMessage.setContent(content);
                      responseMessage.setFromId(fromId);
                      responseMessage.setFromName(fromName);
                      responseMessage.setHeadImage(headImage);
                      String response = objectMapper.writeValueAsString(responseMessage);
                      onlineManager.getSessionById(userId).sendMessage(new TextMessage(response));
                      return;
                  }


                   responseMessage.setType(WebSocketTypeEnum.MESSAGE.val);
                   responseMessage.setContent(content);
                   responseMessage.setFromId(fromId);
                   responseMessage.setFromName(fromName);
                   responseMessage.setSessionId(sessionId);
                   responseMessage.setHeadImage(headImage);
                   // 构造响应
                   String response = objectMapper.writeValueAsString(responseMessage);

                   //


                   // 发送消息给会话中的其他用户(用户在线 )
                   Friend[] friends = friendMapper.getAllFriendListBySessionId(sessionId) ;
                   for(Friend friend : friends){
                     // 如果用户在线就发给他
                       if(onlineManager.getSessionById(friend.getFriendId()) != null){
                           onlineManager.getSessionById(friend.getFriendId()).sendMessage(new TextMessage(response));
                       }
                   }
                   // 保存消息到数据库
                  int result =   messageMapper.insertMessage(responseMessage) ;
                  if(result < 1){
                      log.error("消息添加失败");
                  }
               break;
               }
               case 2: {
                   // 构造信息
                   Add add = new Add() ;
                    add.setType(WebSocketTypeEnum.ADD.val);
                    add.setFromId(userId);
                    add.setFromName(fromName);
                    add.setHeadImage(headImage);
                    add.setUserId(target);

                   // 构造响应
                   String response = objectMapper.writeValueAsString(add);
                   // 如果用户在线就发给他
                   if(onlineManager.getSessionById( target) != null){
                       onlineManager.getSessionById(target).sendMessage(new TextMessage(response));
                   }
                   // 存储信息
                   int result =  addFriendMapper.insert(add) ;
                   if(result < 1){
                       log.error("消息添加失败");
                   }
                   break;
               }
               case 3:{


                   break;
               }
           }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        UserInfo userInfo = (UserInfo) session.getAttributes().get(Constants.USERINFO_KEY);
        if(userInfo == null || userInfo.getUserId()<1){
            log.error("无法获取userInfo属性");
            return;
        }
        //  删除之前,要先判断要删除的是否是当前WebSocketSession
        if(onlineManager.getSessionById(userInfo.getUserId()) == session){
            onlineManager.downLine(userInfo.getUserId());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        UserInfo userInfo = (UserInfo) session.getAttributes().get(Constants.USERINFO_KEY);
        if(userInfo == null || userInfo.getUserId()<1){
            log.error("无法获取userInfo属性");
            return;
        }
        //  删除之前,要先判断要删除的是否是当前WebSocketSession
        if(onlineManager.getSessionById(userInfo.getUserId()) == session){
            onlineManager.downLine(userInfo.getUserId());
        }
    }
}
